package cn.ren.cloud.mq.listener;

import cn.ren.cloud.domain.PayFlow;
import cn.ren.cloud.dto.CourseOrderExtParamsDto;
import cn.ren.cloud.dto.PayTxLocalHandlerDto;
import cn.ren.cloud.service.IPayFlowService;
import cn.ren.cloud.service.IPayOrderService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author 23508
 */
@Slf4j
@Component
@RocketMQTransactionListener(txProducerGroup = "pay-order-group")
public class CourseOrderPayListener implements RocketMQLocalTransactionListener {

    private final IPayOrderService payOrderService;
    private final IPayFlowService payFlowService;

    public CourseOrderPayListener(IPayOrderService payOrderService, IPayFlowService payFlowService) {
        this.payOrderService = payOrderService;
        this.payFlowService = payFlowService;
    }

    /**
     * 本地事务方法执行
     *
     * @param message
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            if (arg == null) {
                log.error("支付结果处理失败，失败原因为：没有执行本地事务相关参数！");
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            PayTxLocalHandlerDto payTxLocalHandlerDto = JSON.parseObject(JSON.toJSONString(arg), PayTxLocalHandlerDto.class);
            // 执行本地事务
            payOrderService.payResultHandler(payTxLocalHandlerDto);
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 本地事务方法回调
     *
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        byte[] bytes = (byte[]) message.getPayload();
        // 判断是否为空
        if (bytes.length == 0) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        CourseOrderExtParamsDto courseOrderExtParamsDto = JSON.parseObject(new String(bytes, StandardCharsets.UTF_8), CourseOrderExtParamsDto.class);
        // 查询支付流程的订单号
        PayFlow payFlow = payFlowService.selectByOrderNo(courseOrderExtParamsDto.getOrderNo());

        if (payFlow == null) {
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        return RocketMQLocalTransactionState.COMMIT;
    }
}
